<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="handleSearch"
            @reset="reset('queryTempletsForm')"
        >
            <el-form ref="queryTempletsForm" :model="queryTempletsForm" label-position="right" label-width="90px">
                <el-row :gutter="24" style="height: 50px;">
                     <el-col :span="8">
                        <el-form-item label="年级:" prop="grade"
                            :error="(queryTempletsForm.projId=='1' && !queryTempletsForm.grade && !!queryTempletsForm.faculty) ? $t('culture.rules.plsChooseGrade'):''"
                        >
                            <el-date-picker
                                v-model="queryTempletsForm.grade"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                                @change="(queryTempletsForm.projId=='1') ? queryCampusMajor() : ''"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学院:" prop="faculty" style="height:32px;">
                            <el-select
                                v-model="queryTempletsForm.faculty"
                                filterable clearable
                                style="width: 100%"
                                @change="queryCampusMajor"
                                :disabled="role != 4" 
                            >
                                <el-option
                                    v-for="item in options.faculty"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <template v-if="queryTempletsForm.projId == '1'">
                        <el-col :span="8">
                            <el-form-item filterable label="校内专业:" prop="campusProfession">
                                <el-select v-model="queryTempletsForm.campusProfession" style="width: 100%" clearable>
                                    <el-option
                                        v-for="item in options.campusProfessions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <template v-else>
                        <el-col :span="8">
                            <el-form-item filterable label="专业:" prop="major">
                                <el-select v-model="queryTempletsForm.major" style="width: 100%" clearable>
                                    <el-option
                                        v-for="item in options.major"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="学习形式:" prop="formLearning">
                                <el-select
                                    v-model="queryTempletsForm.formLearning"
                                    style="width: 100%"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in options.formLearning"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="培养类别:" prop="trainingCategory">
                                <el-select
                                    v-model="queryTempletsForm.trainingCategory"
                                    style="width: 100%"
                                    clearable multiple collapse-tags
                                >
                                    <el-option
                                        v-for="item in options.trainingCategory"
                                        :key="item.code"
                                        :label="item.name"
                                        :value="item.code"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <el-col :span="8">
                        <el-form-item label="培养层次:" prop="trainingLevel">
                            <el-select v-model="queryTempletsForm.trainingLevel" style="width: 100%" clearable>
                                <el-option
                                    v-for="item in options.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="审核状态:" prop="status">
                            <el-select v-model="queryTempletsForm.status" style="width: 100%" clearable>
                                <el-option
                                    v-for="item in options.status"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col> -->
                    <el-col v-if="queryTempletsForm.projId == '1'" :span="8">
                        <el-form-item label="类别:" prop="professionCateGory">
                            <el-select v-model="queryTempletsForm.professionCateGory" style="width: 100%;" clearable>
                                <el-option
                                    v-for="item in options.professionCateGory"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="queryTempletsForm.projId != '1'">
                        <el-form-item :label="$t('culture.scheme.degreeType') + ':'">
                            <el-select v-model="queryTempletsForm.degreeType" clearable style="width: 100%;"
                             @change="queryCampusMajor"
                            >
                                <el-option
                                    v-for="item in options.degreeType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ConditionCard>
        <!-- <el-card shadow="never" body-style="padding: 24px 24px 6px 24px;">
            <el-form
                ref="queryTempletsForm"
                :model="queryTempletsForm"
                label-position="left"
                label-width="90px"
            >
                <el-row :gutter="24" style="height: 50px;">
                    <el-col :span="6">
                        <el-form-item label="管理部门:">
                            <el-select
                                v-model="queryTempletsForm.projId"
                                style="width: 100%"
                                placeholder="选择管理部门"
                                @change="queryTemplets"
                            >
                                <el-option
                                    v-for="item in options.projId"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col> 
                    <el-col :span="6">
                        <el-form-item label="年级:" prop="year">
                            <el-date-picker
                                v-model="queryTempletsForm.year"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                                @change="queryTemplets"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="培养层次:" prop="trainingLevel">
                            <el-select
                                v-model="queryTempletsForm.trainingLevel"
                                style="width: 100%"
                                @change="queryTemplets"
                            >
                                <el-option
                                    v-for="item in options.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="queryTempletsForm.projId != '1'" :span="6">
                        <el-form-item label="学习形式:">
                            <el-select
                                v-model="queryTempletsForm.formLearning"
                                style="width: 100%"
                                @change="queryTemplets"
                            >
                                <el-option
                                    v-for="item in options.formLearning"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="queryTempletsForm.projId == '1'" :span="6">
                        <el-form-item label="类别:" prop="professionCateGory">
                            <el-select
                                v-model="queryTempletsForm.professionCateGory"
                                style="width: 100%;"
                                @change="queryTemplets"
                            >
                                <el-option
                                    v-for="item in options.professionCateGory"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="模板名称:" prop="templateId">
                            <el-select v-model="queryTempletsForm.templateId" style="width: 100%;">
                                <el-option
                                    v-for="item in options.templates"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" class="float-right">
                        <el-form-item class="float-right no-bottom no-right">
                            <el-button
                                @click="reset('queryTempletsForm')"
                            >{{ $t('common.btn.reset') }}</el-button>
                            <el-button
                                type="primary"
                                @click="handleSearch"
                            >{{ $t('common.btn.filter') }}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card> -->
        <el-card shadow="never" body-style="padding: 24px;" class="card-margin">
            <h1 class="condition-title">{{ $t('common.text.list') }}</h1>
            <div class="div-main clearfix">   
                <div class="float-left">
                    <el-input
                        v-model="queryTempletsForm.name"
                        placeholder="培养方案名称"
                        suffix-icon="el-icon-search"
                        @change="handSearchChang"
                    />
                </div>
                <div class="float-right">
                    <el-button
                        @click="batchEdit"
                    >{{ $t('common.btn.batch') + $t('common.btn.edit') }}</el-button>
                </div>
            </div>
            <el-table
                :data="tableData"
                ref="cultureSchemesTable"
                stripe
                style="width: 100%"
                :cell-class-name="cellStyleMethod"
                tooltip-effect="light"
                @selection-change="selectionChange"

            >
                <el-table-column type="selection" width="55"/>
                <el-table-column label="方案名称" prop="name" show-overflow-tooltip min-width="150"/>
                <el-table-column label="年级" prop="grade" width="80"/>
                <el-table-column label="培养层次" prop="trainingLevelI18n" width="80"/>
                <el-table-column v-if="queryTempletsForm.projId != '1'" label="学位类型" prop="degreeTypeI18n" width="80"  show-overflow-tooltip/>
                <el-table-column label="学院" prop="facultyI18n" show-overflow-tooltip/>
                <div v-if="queryTempletsForm.projId == '1'">
                    <el-table-column label="类别" width="100">
                        <template
                            slot-scope="scope"
                        >{{ scope.row.professionCateGory=="1"? "专业大类": "专业" }}</template>
                    </el-table-column>
                </div>
                <template v-if="queryTempletsForm.projId == '1'">
                    <el-table-column label="校内专业" prop="campusProfessionName" min-width="100"/>
                </template>
                <template v-if="queryTempletsForm.projId != '1'">
                    <el-table-column label="专业" prop="majorI18n" min-width="150"/>
                    <el-table-column label="学习形式" prop="formLearningI18n" width="100"/>
                    <el-table-column label="培养类别" prop="trainingCategoryI18n" width="100" show-overflow-tooltip/>
                </template>

                <el-table-column label="审核状态" prop="status" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == 3" type="success" size="mini">通过</el-tag>
                        <el-tag v-if="scope.row.status == 1" type="info" size="mini">草稿</el-tag>
                        <el-tag v-if="scope.row.status == 2" type="warning" size="mini">审核中</el-tag>
                        <el-tag v-if="scope.row.status == 4" type="danger" size="mini">禁用</el-tag>
                        <el-tag v-if="scope.row.status == 5" type="danger" size="mini">变更中</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80px">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="editRow(scope.row.id,scope.row.trainingLevel)"
                        >{{ $t('common.btn.edit') }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        :current-page="queryTempletsForm.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="queryTempletsForm.pageSize_"
                        :total="queryTempletsForm.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float: right;margin:0;"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </div>
        </el-card>
        <ChangeCultureScheme
            :is-show="showBatchModifyDialog"
            :culture-schemes="cultureSchemes"
            :current-templet="currentTemplet"
            :current-details="queryTempletsForm"
            :projId="queryTempletsForm.projId"
            :training-level="trainingLevel"
            v-on:change-visible="changeVisible"
        />
    </div>
</template>
<script>
import bus from 'common/src/utils/bus';
import * as API from "common/src/api/culture/cultruescheme";
import UTILS from "common/src/utils/utils";
import { findFaculty } from "common/src/api/faculty";
import { queryDic, findTrainingLevelByProjId,sortTrainingCategories } from "common/src/api/dictionary";
import ChangeCultureScheme from "./ChangeCultureScheme";
import { getCultureTemplateList } from "common/src/api/courseTemplate";
import { getPower } from 'common/src/api/culture/culturePlan';
import { getGraduateDegreePage } from "common/src/api/resource/course";
export default {
    components: { ChangeCultureScheme },
    data() {
        return {
            queryTempletsForm: {
                grade: "", // 年级
                trainingLevel: "", // 培养层次
                faculty: "", // 学院
                major: "", // 专业
                degreeType: "", // 学位类型
                formLearning: "", // 学习形式
                spcialPlan: "", // 专项计划
                studentAbroad: "", // 国际学生
                //status: "1", // 状态
                name: "", // 名称
                pageNum_: 1,
                pageSize_: 20,
                total: 0,
                projId: "1",
                professionCateGory: "",
                trainingCategory: []
            },
            queryCultureSchemesForm: {
                name: "", // 名称
                pageNum_: 1,
                pageSize_: 20,
                total: 0,
                templateId: ""
            },
            options: {
                grade: [],
                trainingLevel: [],
                faculty: [],
                major: [],
                batchCultrueSchemeMajor: [],
                degreeType: [],
                spcialPlan: [],
                formLearning: [],
                studentAbroad: [],
                status: [
                    {
                        label: "通过",
                        value: 3
                    },
                    {
                        label: "草稿",
                        value: 1
                    },
                    {
                        label: "审核中",
                        value: 2
                    },
                    {
                        label: "禁用",
                        value: 4
                    },
                    {
                        label: "变更中",
                        value: 5
                    }
                ],
                templateName: [],
                degreeType: [], // 学位类型
                degreeCategory: [], // 学位类别
                trainingCategory: [], // 培养类别,
                professionCateGory: [
                    { value: "1", label: "专业大类" },
                    { value: "2", label: "专业" }
                ],
                templates: [],
                campusProfessions: [],
                trainingCategoryId: [],
                projId: []
            },
            tableData: [],
            showBatchModifyDialog: false,
            cultureSchemes: [],
            role:'',
            currentTemplet: "",
            trainingLevel:''
        };
    },

    created() {
        this.init();
        this.getRole();
        this.handleSearch();
        bus.$on('updateCurrentManageDeptId', (currentManageDeptId) => {
            this.queryTempletsForm.projId = currentManageDeptId;
            this.queryTemplets();
            //this.handleChange();
        })
    },
    methods: {
        cellStyleMethod({row, column, rowIndex, columnIndex}){
            if (columnIndex == 1) {
                return 'normal-cell';
            }
        },
        init() {
            this.initOptions();
            this.initProjId();
            this.queryTemplets();
            //this.handleChange();
        },
        initProjId() {
            let currentUser = (this.$store.state.session.user && this.$store.state.session.user.currentRole) || JSON.parse(localStorage.getItem('user'));
            this.queryTempletsForm.projId = currentUser.currentManageDptId;
        },
        queryTemplets() {
            // let param = this.getQueryTempletsParam();
            // getCultureTemplateList(this.queryTempletsForm).then(response => {
            //     if (response.code === 200) {
            //         this.options.templates = trans(response.data.list);
            //         this.queryTempletsForm.templateId = "";
            //         this.queryTempletsForm.total = response.data.total_;
            //     }
            // });
            // function trans(list) {
            //     return list.map(item => {
            //         return { label: item.name, value: item.id };
            //     });
            // }
        },
        getQueryTempletsParam() {
            let param = Object.assign({}, this.queryTempletsForm);
            if (param.projId == 1) delete param.formLearning;
            else delete param.professionCateGory;
            return param;
        },
         getRole(){
            getPower().then((res) => {
                this.role = res.data.power
                if(res.data.departmentCode.indexOf(",") !=-1){
                    let departmentCode = res.data.departmentCode.split(",")
                    this.queryTempletsForm.faculty = departmentCode[0]
                }else{
                    this.queryTempletsForm.faculty = res.data.departmentCode
                }
                if(res.data.departmentCode && res.data.power == 3){
                    this.queryCampusMajor()
                }
            })
        },
        initOptions() {
            findFaculty().then(res => { 
                let data = {"X_YX": res.data};
                UTILS.fillSelect({ faculty: "X_YX" }, data, this.options);
            });
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: [
                    "X_PYCC",
                    "K_XXXS",
                    "X_ZXJH",
                    "X_PYLB",
                    "X_XWLB",
                    "X_XWLX",
                    "X_GLBM" ,
                    "X_PYCC"
                ]
            };
            queryDic(data)
                .then(res => {
                    let params = {
                        lang: this.$store.getters.language,
                        keys: ["X_PYLB"]
                    };
                    sortTrainingCategories(params).then((res) => {
                        this.options.trainingCategory = res.data.X_PYLB;
                    });
                    if (res.code === 200) {
                        // this.fillSelect(res.data);
                        UTILS.fillSelect(
                            {
                                degreeCategory: "X_XWLB",
                                spcialPlan: "X_ZXJH",
                                formLearning: "K_XXXS",
                                degreeType: "X_XWLX",
                                // trainingCategory: "X_PYLB",
                                project: "X_GLBM",
                                trainingLevel: "X_PYCC",
                            },
                            res.data,
                            this.options
                        );
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        queryCampusMajor() { // 综合查询专业（本研不分）
            if (this.queryTempletsForm.projId == "1") {
                this.queryCampusProfessions(this.queryTempletsForm);
            } else this.queryMajors(this.queryTempletsForm.faculty,this.queryTempletsForm.degreeType);
        },
        queryCampusProfessions(query) { // 查询校内专业（本科生）
            this.options.campusProfessions = [];
            Vue.set(this.queryTempletsForm, "campusProfession", "");
            // 联动校验
            if(!(query.grade && query.faculty)) {
              return
            }
            if(query.professionCateGory){
                query.category = query.professionCateGory;
            }else{
                query.category = query.category;
            }
            API.findProfessionByParam(query).then(res => {
                if (res.code === 200) {
                    this.options.campusProfessions = res.data.map(
                        (item, index) => {
                            return {
                                label: item.professionCateGoryName,
                                value: item.professionCateGory
                            };
                        }
                    );
                }
            });
        },
        queryMajors(college,degreeType) { // 查询专业（研究生）
            this.options["major"] = [];
            Vue.set(this.queryTempletsForm, "major", "");
            let promise = this.getGraduateDegreePage(college,degreeType);
            promise.then(response => {
                let {
                    code,
                    data: { list }
                } = response;
                if (code === 200) {
                    this.options.major = list.map(item => ({
                        value: item.code,
                        label:
                            "cn" === this.$store.getters.language
                                ? item.name
                                : item.nameEn
                    }));
                }
            });
        },
        getGraduateDegreePage(college,degreeType) {
            const data = {
                college: college,
                type:degreeType,
                page: false,
                isRecruit: 1,
            };
            return getGraduateDegreePage(data);
        },
        reset(ref) {
            if(this.role == 3){
                this.$refs[ref].resetFields();
                 this.queryTempletsForm.degreeType ='';
                this.getRole();
                this.handleSearch();
            }else{
                this.$refs[ref].resetFields();
                this.queryTempletsForm.degreeType ='';
                this.handleSearch();
            }
        },
        handSearchChang(){
            this.handleSearch();
        },
        handleSearch() {
            // if (!this.queryTempletsForm.templateId) {
            //     this.$message({
            //         type: "warning",
            //         message: "请先选择要培养模板!"
            //     });
            //     return;
            // }
            //this.queryCultureSchemesForm.templateId = this.queryTempletsForm.templateId;
            API.findCultureSchemeList(
                this.queryTempletsForm
            ).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.list;
                    this.queryTempletsForm.total = res.data.total_;
                }
            });
        },
        selectionChange(list) {
            this.cultureSchemes = list.map(ele => {
                return ele.id;
            });
        },
        handleSizeChange(val) {
            this.queryTempletsForm.pageSize_ = val;
            this.handleSearch();
        },
        handleCurrentChange(val) {
            this.queryTempletsForm.pageNum_ = val;
            this.handleSearch();
        },
        editRow(id,trainingLevel) {
            this.$refs.cultureSchemesTable.clearSelection();
            this.cultureSchemes = [id];
            this.trainingLevel = trainingLevel
            this.showModify();
        },
        showModify() {
            // if (!this.queryCultureSchemesForm.templateId) {
            //     this.$message({
            //         type: "warning",
            //         message: "请至少选择培养模板!"
            //     });
            //     return;
            // }
            //this.currentTemplet = this.queryCultureSchemesForm.templateId;
            this.showBatchModifyDialog = true;
        },
        batchEdit() {
            if (this.$refs.cultureSchemesTable.selection.length === 0) {
                this.$message({
                    message: "请先选择要编辑的方案!",
                    type: "warning"
                });
                return;
            }
            this.trainingLevel = ""
            this.showModify();
        },
        changeVisible() {
            this.showBatchModifyDialog = false;
            this.cultureSchemes = [];
            this.$refs.cultureSchemesTable.clearSelection();
        },
         loadTrainingLevelOptions(optionKey, dataObj) {
            this.options[optionKey] = [];
            _.each(dataObj, level => {
                this.options[optionKey].push({
                    label:
                        "en" === this.$store.getters.language
                            ? level.nameEN
                            : level.nameCN,
                    value: level.code
                });
            });
        },
        // handleChange() {
        //     findTrainingLevelByProjId(this.queryTempletsForm.projId).then(res => {
		// 	    if (res.code === 200) {
		// 	        this.queryTempletsForm.trainingLevel = "";
		// 	        this.loadTrainingLevelOptions("trainingLevel", res.data);
		// 	    }
		// 	});
        // }
    }
};
</script>
<style scoped>
.div-main {
    margin-bottom: 16px;
  }
</style>
